var getShopIdList = require('./crawlerV2_idlist.js');
var DzdpApi = require('./api_dzdp.js');


var limitSize = 10; // -1表示不限制

getShopIdList(function(idList) {
	var index = 0;
	var max = idList.length;
	if (limitSize > 0 && max > limitSize) {
		max = limitSize;
	}


	function foo() {
		if (index >= max) return;

		// 
		var businessId = idList[index];
		index++;
		getBusinessInfo(businessId, function(err, result) {
			if (err) {
				console.log(err);
				return foo();
			}

			saveToDb(result, function(err, result) {
				if (err) {
					console.log(err);
				}
				foo();
			});
		});
	}

	foo();
});

var dzdpApi = new DzdpApi();

function getBusinessInfo(businessId, cb) {
	dzdpApi.get_single_business(businessId, function(err, result) {
		if (err) {
			console.log('get_single_business err', err);
		} else {
			// console.log(result);
			console.log('getBusinessInfo succ');
		}
		cb(err, result);
	});
}



var request = require('request');
var url = 'http://localhost:9200/o2o_service/shop/';

function saveToDb(strObj, cb) {
	// console.log('saveToDb');
	// console.log(strObj);
	// console.log(typeof strObj);

	var info = JSON.parse(strObj);
	if (info.status !== 'OK') {
		return cb('status not ok');
	}
	var count = info.count;
	if (info.count === 0) {
		console.log('count = 0');
		console.log(strObj);
		return cb('count = 0');
	}
	var businesses = info.businesses;
	var shop = businesses[0]; // only one
	// console.log(shop);

	request({
		method: 'PUT',
		url: url + shop.business_id,
		json: true,
		headers: {
			"content-type": "application/json",
		},
		body: shop
	}, function(err, response, body) {
		if (err) {
			console.log('save to es fail:', err);
			return cb(err);
		}
		console.log('save to es success');
		console.log(body);
		cb(null, body);
	});
}